package com.seed.service.sysmanager;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.seed.commons.dbquery.PageModelForSQL;
import com.seed.commons.dbutil.DB;
import com.seed.commons.dbutil.DBBean;
import com.seed.commons.util.PinyinUtil;
import com.seed.commons.util.RandomUtil;
import com.seed.web.form.sysmanager.EmployeeForm;
import com.seed.web.form.sysmanager.InsideUserForm;

@Service
public class EmployeeService implements IEmployee{
	
	private Log log = LogFactory.getLog(getClass()) ;

	@Resource
	private IInsideUser insideUser ;
	
	@Override
	public boolean saveEmployee(EmployeeForm emp) {
		
		String sql = "INSERT INTO SEED_EMP(" +
				"EmpNo,EmpName,EmpSex," +
				"Nation,Birthday,School," +
				"Natives,EmpAddr,MobileTel," +
				"Tel,Email,EmpImgPath," +
				"EntryDate,DeptNoFK) " +
				"VALUES(?,?,?,?,TO_DATE(?,'yyyy-MM-dd'),?,?,?,?,?,?,?,TO_DATE(?,'yyyy-MM-dd'),?)" ;
		
		try {
			String empno = "SEED-"+RandomUtil.getRandomNum(5) ;
			DB.insert(sql, new Object[]{empno,
					emp.getEmpName(),emp.getEmpSex(),emp.getNation(),emp.getBirthday(),
					emp.getSchool(),emp.getNatives(),emp.getEmpAddr(),emp.getMobileTel(),
					emp.getTel(),emp.getEmail(),emp.getEmpImgPath(),emp.getEntryDate(),
					emp.getDeptNoFK()}) ;
			
			//初始化员工登陆账号
			InsideUserForm iu = new InsideUserForm() ;
			iu.setUserName(PinyinUtil.getPinYin(emp.getEmpName())) ;
			iu.setEmpNoFK(empno) ;
			this.insideUser.saveInsideUser(iu) ;
			
			return true ;
		} catch (Exception e) {
			e.printStackTrace();
			log.info("数据插入出错：" + e.getMessage());
			log.info("执行SQL：" + sql);
		}
		return false;
	}

	@Override
	public void deleteEmployee(String id) {
		
		
	}

	@Override
	public void updateEmployee(EmployeeForm emp) {
		
		
	}

	@Override
	public DBBean queryEmployeeById(String id) {
		
		return null;
	}

	@Override
	public PageModelForSQL getScrollData(int currentPage, int lineSize) {
		String sql = "SELECT * FROM " +
				 "(" +
					 "SELECT " +
					 "ROWNUM rn,t1.* " +
					 "FROM (SELECT * from SEED_EMP) t1 " +
					 "WHERE ROWNUM <= ?" +
				 ") " +
				 "WHERE rn > ? ORDER BY SORTDATE DESC" ;
		String count = "SELECT COUNT(*) c FROM SEED_EMP";
		
		try {
			PageModelForSQL pm = new PageModelForSQL();
			pm.setResultList(DB.query(sql,
					new Object[] { lineSize, currentPage }));
			pm.setTotalRecord(Long.parseLong(DB.getBeanFirst(count, null)
					.getbean("c").toString()));

			return pm;
		} catch (Exception e) {
			log.info("分页查询出错：" + e.getMessage());
		}
		return null;
	}

}
